<?php

use Phphub\Core\CreatorListener;

class CommentsController extends \BaseController implements CreatorListener
{
    public function __construct()
    {
        parent::__construct();
        $this->beforeFilter('auth');
    }

    public function authorOrAdminPermissioinRequire($author_id)
    {
        if (! Entrust::can('manage_comments') && $author_id != Auth::id()) {
            throw new ManageCommentsException("permission-required");
        }
    }

    public function store()
    {
        return App::make('Phphub\Creators\CommentCreator')->create($this, Input::except('_token'));
    }

    public function vote($id)
    {
        $comment = Comment::find($id);
        App::make('Phphub\Vote\Voter')->commentUpVote($comment);
        return Redirect::route('issues.show', [$comment->issue_id, '#comment'.$comment->id]);
    }

    public function destroy($id)
    {
        $comment = Comment::findOrFail($id);
        $this->authorOrAdminPermissioinRequire($comment->user_id);
        $comment->delete();

        $comment->issue->decrement('comment_count', 1);

        Flash::success(lang('Operation succeeded.'));

        return Redirect::route('issues.show', $comment->issue_id);
    }

    /**
     * ----------------------------------------
     * CreatorListener Delegate
     * ----------------------------------------
     */

    public function creatorFailed($errors)
    {
        Flash::error(lang('Operation failed.'));
        return Redirect::back();
    }

    public function creatorSucceed($comment)
    {
        Flash::success(lang('Operation succeeded.'));
        return Redirect::route('issues.show', array(Input::get('issue_id'), '#comment'.$comment->id));
    }
}
